﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Framework.ObjectPool;

namespace Framework.ObjectFactory
{
    public static class OjbectPoolFactory<TType> where TType : class
    {
        private static Dictionary<Type, Pool> dicTypePoolCollection = new Dictionary<Type, Pool>();
        private static object lockObj = new object();

        public static TType GetInstance()
        {
            Type type = typeof(TType);
            Pool pool = null;
            if (!dicTypePoolCollection.TryGetValue(type, out pool))
            {
                lock (lockObj)
                {
                    if (!dicTypePoolCollection.TryGetValue(type, out pool))
                    {
                        pool = new Pool(() => { return Construct(); });
                        dicTypePoolCollection[type] = pool;
                    }
                }
            }

            return (TType)pool.GetInstance();
        }

        public static void ReturnToPool(TType obj)
        {
            Type type = typeof(TType);
            Pool pool = null;
            if (dicTypePoolCollection.TryGetValue(type, out pool))
            {
                pool.Return((IPoolInstance)obj);
            }
        }

        private static IPoolInstance Construct()
        {
            Type type = ProxyBuilder.BuildType<TType, ObjectProxyPoolClassBuilder<TType>>();
            return (IPoolInstance)Activator.CreateInstance(type);
        }
    }
}
